package com.zhangsr.zus.remoting.netty;

import com.zhangsr.zus.common.Constants;
import com.zhangsr.zus.common.URL;
import com.zhangsr.zus.remoting.api.Codec2;
import com.zhangsr.zus.remoting.api.buffer.ChannelBuffers;
import com.zhangsr.zus.remoting.api.buffer.DynamicChannelBuffer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.MessageToByteEncoder;

import java.io.IOException;

/**
 * @Author: zhangsr
 */
final class NettyCodecAdapter {

    private final ChannelHandler encoder = new InternalEncoder();

    private final ChannelHandler decoder = new InternalDecoder();

    private final Codec2 codec;

    private final URL url;

    private final int bufferSize;

    private final com.zhangsr.zus.remoting.api.ChannelHandler handler;

    public NettyCodecAdapter(Codec2 codec, URL url, com.zhangsr.zus.remoting.api.ChannelHandler handler) {
        this.codec = codec;
        this.url = url;
        this.handler = handler;
        int b = url.getPositiveParameter(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE);
        this.bufferSize = b >= Constants.MIN_BUFFER_SIZE && b <= Constants.MAX_BUFFER_SIZE ? b : Constants.DEFAULT_BUFFER_SIZE;
    }

    public ChannelHandler getEncoder() {
        return encoder;
    }

    public ChannelHandler getDecoder() {
        return decoder;
    }

    @Sharable
    private class InternalEncoder extends MessageToByteEncoder {

        @Override
        protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
            Channel ch = ctx.channel();

            com.zhangsr.zus.remoting.api.buffer.ChannelBuffer buffer = com.zhangsr.zus.remoting.api.buffer.ChannelBuffers.dynamicBuffer(1024);
            NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler);
            try {
                codec.encode(channel, buffer, msg);
                // netty5 use ByteBuf writeBytes.
                out.writeBytes(buffer.toByteBuffer());
            } finally {
                NettyChannel.removeChannelIfDisconnected(ch);
            }
            ChannelBuffers.wrappedBuffer(buffer.toByteBuffer());
        }
    }

    private class InternalDecoder extends SimpleChannelInboundHandler {

        private com.zhangsr.zus.remoting.api.buffer.ChannelBuffer buffer =
                com.zhangsr.zus.remoting.api.buffer.ChannelBuffers.EMPTY_BUFFER;

        @Override
        protected void messageReceived(ChannelHandlerContext ctx, Object o) throws Exception {
            if (!(o instanceof ByteBuf)) {
                return;
            }

            ByteBuf input = (ByteBuf) o;
            int readable = input.readableBytes();
            if (readable <= 0) {
                return;
            }

            com.zhangsr.zus.remoting.api.buffer.ChannelBuffer message;
            System.out.println("----->buffer.readable:" + buffer.readable());
            if (buffer.readable()) {
                if (buffer instanceof DynamicChannelBuffer) {
                    System.out.println("----->buffer is DynamicChannelBuffer.");
                    buffer.writeBytes(input.nioBuffer());
                    message = buffer;
                } else {
                    System.out.println("----->buffer ChannelBuffers.dynamicBuffer.");
                    int size = buffer.readableBytes() + input.readableBytes();
                    message = com.zhangsr.zus.remoting.api.buffer.ChannelBuffers.dynamicBuffer(size > bufferSize ? size : bufferSize);
                    message.writeBytes(buffer, buffer.readableBytes());
                    message.writeBytes(input.nioBuffer());
                }
            } else {
                System.out.println("----->buffer ChannelBuffers.wrappedBuffer.");
                message = com.zhangsr.zus.remoting.api.buffer.ChannelBuffers.wrappedBuffer(input.nioBuffer());
            }

            NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler);
            Object msg;
            int saveReaderIndex;

            try {
                do {
                    saveReaderIndex = message.readerIndex();
                    try {
                        System.out.println("readerIndex :" + message);
                        msg = codec.decode(channel, message);
                        System.out.println("decode msg :" + msg);
                    } catch (IOException e) {
                        buffer = com.zhangsr.zus.remoting.api.buffer.ChannelBuffers.EMPTY_BUFFER;
                        throw e;
                    }
                    if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) {
                        System.out.println("======>Codec2.DecodeResult.NEED_MORE_INPUT");
                        message.readerIndex(saveReaderIndex);
                        break;
                    } else {
                        if (saveReaderIndex == message.readerIndex()) {
                            buffer = com.zhangsr.zus.remoting.api.buffer.ChannelBuffers.EMPTY_BUFFER;
                            throw new IOException("Decode without read data.");
                        }
                        if (msg != null) {
                            System.out.println("fireMessageReceived. remoteAddress:" + ctx.channel().remoteAddress());
                            ctx.fireChannelRead(msg);
                        }
                    }
                } while (message.readable());
            } finally {
                if (message.readable()) {
                    message.discardReadBytes();
                    buffer = message;
                } else {
                    buffer = com.zhangsr.zus.remoting.api.buffer.ChannelBuffers.EMPTY_BUFFER;
                }
                NettyChannel.removeChannelIfDisconnected(ctx.channel());
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        }

    }
}
